简书链接:原创shell添加回环网络适配器LoopbackAdapter
文章字数:230,阅读全文大约需要1分钟

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18


Get-NetAdapter | Where-Object -Property DriverDescription -eq 'Microsoft KM-TEST Loopback Adapter'

Get-NetAdapter -Name 192.168.110.8 -ErrorAction SilentlyContinue

Rename-NetAdapter -Name $adapter.Name -NewName $Name -ErrorAction Stop
Write-Verbose -Message ("name is{0}" -f "FF")


New-LoopbackAdapter -Name IP_REDIRECT -Force

{4d36e972-e325-11ce-bfc1-08002be10318}



Rename-NetAdapter -Name $adapter.Name -NewName $Name -ErrorAction Stop

其原理就是执行devcon64.exe install C:\WINDOWS\inf\netloop.inf *MSLOOP就会自动产生一个适配器

循环插入

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
Install-Module -Name LoopbackAdapter
Import-Module -Name LoopbackAdapter

$val = 0

while($val -lt 2) {
$val++ ;

# The name for the loopback adapter interface that will be created.
$loopback_name = "LoopbackAAA$val"

New-LoopbackAdapter -Name $loopback_name -Force

# Commented this line out but you're probably gonna want it so you don't end up like me
#Get-NetAdapter $loopback_name | Set-DNSClient –RegisterThisConnectionsAddress $False

Write-Host $val
}

New-LoopbackAdapter -Name test -Force

可以参考源码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
#Region './prefix.ps1' 0
<#
.EXTERNALHELP LoopbackAdapter-help.xml
#>

$moduleRoot = Split-Path `
-Path $MyInvocation.MyCommand.Path `
-Parent

#region LocalizedData
$culture = 'en-US'

if (Test-Path -Path (Join-Path -Path $moduleRoot -ChildPath $PSUICulture))
{
$culture = $PSUICulture
}

Import-LocalizedData `
-BindingVariable LocalizedData `
-Filename 'LoopbackAdapter.strings.psd1' `
-BaseDirectory $moduleRoot `
-UICulture $culture
#endregion
#EndRegion './prefix.ps1' 23
#Region './Private/Install-Chocolatey.ps1' 0
<#
.SYNOPSIS
Install Chocolatey.

.DESCRIPTION
Installs Chocolatey from the internet if it is not installed.

.PARAMETER Force
Force the install of Chocolatey, without confirming with the user.

.EXAMPLE
Install-Chocolatey

.OUTPUTS
None
#>
function Install-Chocolatey
{
[CmdLetBinding(
SupportsShouldProcess = $true,
ConfirmImpact = 'High')]
param
(
[Parameter()]
[Switch]
$Force
)

# Check chocolatey is installed - if not, install it
$chocolateyInstalled = Test-Path -Path (Join-Path -Path $ENV:ProgramData -ChildPath 'Chocolatey\Choco.exe')

if (-not $chocolateyInstalled)
{
if ($Force -or $PSCmdlet.ShouldProcess($LocalizedData.DownloadAndInstallChocolateyShould))
{
Write-Verbose -Message $LocalizedData.InstallingChocolateyMessage
try
{
$chocolateyInstallScript = (Invoke-WebRequest -UseBasicParsing -Uri 'https://chocolatey.org/install.ps1').Content
$chocolateyInstallScript = [scriptblock]::Create($chocolateyInstallScript)
$null = $chocolateyInstallScript.Invoke()
}
catch
{
throw ($LocalizedData.ChocolateyInstallationError -f $_)
}
}
else
{
throw $LocalizedData.NetworkAdapterExistsWrongTypeError
}
}
else
{
Write-Verbose -Message $LocalizedData.ChocolateyInstalledMessage
}
}
#EndRegion './Private/Install-Chocolatey.ps1' 58
#Region './Private/Install-Devcon.ps1' 0
<#
.SYNOPSIS
Install the DevCon.Portable (Windows Device Console) package using Chocolatey.

.DESCRIPTION
Installs Chocolatey from the internet if it is not installed, then uses
it to download the DevCon.Portable (Windows Device Console) package.
The devcon.portable Chocolatey package can be found here and installed manually
if no internet connection is available:
https://chocolatey.org/packages/devcon.portable/

Chocolatey will remain installed after this function is called.

.PARAMETER Force
Force the install of Chocolatey and the Devcon.portable package if not already
installed, without confirming with the user.

.EXAMPLE
Install-Devcon

.OUTPUTS
The fileinfo object containing the appropriate DevCon*.exe application that was
installed for this architecture.
#>
function Install-Devcon
{
[OutputType([System.IO.FileInfo])]
[CmdLetBinding(
SupportsShouldProcess = $true,
ConfirmImpact = 'High')]
param
(
[Parameter()]
[Switch]
$Force
)

Install-Chocolatey @PSBoundParameters

# Check DevCon installed - if not, install it.
$devConInstalled = ((Test-Path -Path "$ENV:ProgramData\Chocolatey\Lib\devcon.portable\Devcon32.exe") `
-and (Test-Path -Path "$ENV:ProgramData\Chocolatey\Lib\devcon.portable\Devcon64.exe"))

if (-not $devConInstalled)
{
try
{
<#
This will download and install DevCon.exe
It will also be automatically placed into the path
#>
if ($Force -or $PSCmdlet.ShouldProcess($LocalizedData.DownloadAndInstallDevConShould))
{
Write-Verbose -Message $LocalizedData.InstallDevconMessage
$null = & choco @('install','-r','-y','devcon.portable')
}
else
{
throw $LocalizedData.DevConNotInstalledError
}
}
catch
{
throw ($LocalizedData.DevConInstallationError -f $_)
}
}

if ([Environment]::Is64BitOperatingSystem -eq $True)
{
Get-ChildItem -Path "$ENV:ProgramData\Chocolatey\Lib\devcon.portable\Devcon64.exe"
}
else
{
Get-ChildItem -Path "$ENV:ProgramData\Chocolatey\Lib\devcon.portable\Devcon32.exe"
}
}
#EndRegion './Private/Install-Devcon.ps1' 77
#Region './Private/Uninstall-Devcon.ps1' 0
<#
.SYNOPSIS
Install the DevCon.Portable (Windows Device Console) package using Chocolatey.

.DESCRIPTION
Installs Chocolatey from the internet if it is not installed, then uses
it to uninstall the DevCon.Portable (Windows Device Console) package.

Chocolatey will remain installed after this function is called.

.PARAMETER Force
Force the uninstall of the devcon.portable package if it is installed, without confirming with the user.

.EXAMPLE
Uninstall-Devcon

.OUTPUTS
None.
#>
function Uninstall-Devcon
{
[CmdLetBinding(
SupportsShouldProcess = $true,
ConfirmImpact = 'High')]
param
(
[Parameter()]
[Switch]
$Force
)

Install-Chocolatey @PSBoundParameters

try
{
<#
This will download and install DevCon.exe
It will also be automatically placed into the path
#>
if ($Force -or $PSCmdlet.ShouldProcess($LocalizedData.UninstallDevConShould))
{
$null = & choco @('uninstall','-r','-y','devcon.portable')
}
else
{
throw $LocalizedData.DevConNotUninstalledError
}
}
catch
{
throw ($LocalizedData.DevConNotUninstallationError -f $_)
}
}
#EndRegion './Private/Uninstall-Devcon.ps1' 54
#Region './Private/Wait-ForDevconUpdate.ps1' 0
<#
.SYNOPSIS
Waits for changes made by DevCon.exe to complete before continuing.

.DESCRIPTION
Waits for the DevCon.exe process to exit and then checks whether Get-NetAdapter completes successfully.
Get-NetAdapter will throw "Illegal operation attempted on a registry key that has been marked for
deletion." if the changes are still processing.

.PARAMETER DevconExeTimeout
Time in seconds to wait for the DevCon process to complete.

.PARAMETER RegistryUpdateTimeout
Time in seconds to wait for the registry to finish processing changes.

.EXAMPLE
Wait-ForDevconUpdate

.NOTES
N/A
#>
function Wait-ForDevconUpdate
{
[CmdletBinding()]
param
(
[Parameter()]
[System.Int32]
$DevconExeTimeout = 5,

[Parameter()]
[System.Int32]
$RegistryUpdateTimeout = 5
)

Get-Process -Name 'DevCon' -ErrorAction SilentlyContinue | Wait-Process -Timeout $DevconExeTimeout
$registryUpdated = $false
$registryTimer = 0
$waitIncrement = 0.5

while ($registryUpdated -eq $false)
{
try
{
$null = Get-NetAdapter -ErrorAction Stop *>&1
$registryUpdated = $true
}
catch [Microsoft.Management.Infrastructure.CimException]
{
if ($registryTimer -ge $RegistryUpdateTimeout)
{
throw $_
}

Start-Sleep -Seconds $waitIncrement
$registryTimer += $waitIncrement
}
}
}
#EndRegion './Private/Wait-ForDevconUpdate.ps1' 60
#Region './Public/Get-LoopbackAdapter.ps1' 0
function Get-LoopbackAdapter
{
[OutputType([Microsoft.Management.Infrastructure.CimInstance[]])]
[CmdLetBinding()]
param
(
[Parameter()]
[System.String]
$Name
)

# Check for the existing Loopback Adapter
if ($Name)
{
$adapter = Get-NetAdapter `
-Name $Name `
-ErrorAction Stop

if ($adapter.DriverDescription -ne 'Microsoft KM-TEST Loopback Adapter')
{
throw ($LocalizedData.NetworkAdapterExistsWrongTypeError -f $Name)
} # if

return $adapter
}
else
{
Get-NetAdapter | Where-Object -Property DriverDescription -eq 'Microsoft KM-TEST Loopback Adapter'
} # if
}
#EndRegion './Public/Get-LoopbackAdapter.ps1' 31
#Region './Public/New-LoopbackAdapter.ps1' 0

function New-LoopbackAdapter
{
[OutputType([Microsoft.Management.Infrastructure.CimInstance])]
[CmdLetBinding()]
param
(
[Parameter(Mandatory = $true)]
[System.String]
$Name,

[Parameter()]
[switch]
$Force
)

$null = $PSBoundParameters.Remove('Name')

# Check for the existing Loopback Adapter
$adapter = Get-NetAdapter `
-Name $Name `
-ErrorAction SilentlyContinue

# Is the loopback adapter installed?
if ($adapter)
{
throw ($localizedData.NetworkAdapterExistsError -f $Name)
} # if

# Make sure DevCon is installed.
$devConExe = (Install-Devcon @PSBoundParameters).FullName

<#
Get a list of existing Loopback adapters
This will be used to figure out which adapter was just added
#>
$existingAdapters = (Get-LoopbackAdapter).PnPDeviceID

<#
Use Devcon.exe to install the Microsoft Loopback adapter
Requires local Admin privs.
#>
Write-Verbose -Message ($LocalizedData.CreatingLoopbackAdapterMessage -f $Name)
$null = & $DevConExe @('install', "$($ENV:SystemRoot)\inf\netloop.inf", '*MSLOOP')
Wait-ForDevconUpdate

# Find the newly added Loopback Adapter
$adapters = Get-NetAdapter
$adapter = $adapters |
Where-Object -FilterScript { #在已存在列表不包含并且多了一个设备描述为这个的就代表ok.
($_.PnPDeviceID -notin $ExistingAdapters ) -and `
($_.DriverDescription -eq 'Microsoft KM-TEST Loopback Adapter')
}

if (-not $adapter)
{
throw ($LocalizedData.NewNetworkAdapterNotFoundError -f $Name)# The new Loopback Adapter '{0}' was not found.
} # if

# Rename the new Loopback adapter Setting the name of the new Loopback Adapter to '{0}'.
#Write-Verbose -Message ($adapter.Name)
Write-Verbose -Message ($LocalizedData.SettingNameOfNewLoopbackAdapterMessage -f $Name)
$null = Rename-NetAdapter `
-Name $adapter.Name `
-NewName $Name `
-ErrorAction Stop

# Set the metric to 254
Write-Verbose -Message ($LocalizedData.SettingMetricOfNewLoopbackAdapterMessage -f $Name)
$null = Set-NetIPInterface `
-InterfaceAlias $Name `
-InterfaceMetric 254 `
-ErrorAction Stop

<#
Wait till IP address binding has registered in the CIM subsystem.
if after 30 seconds it has not been registered then throw an exception.
#>
[System.Boolean] $adapterBindingReady = $false
[System.DateTime] $startTime = Get-Date

while (-not $adapterBindingReady `
-and (((Get-Date) - $startTime).TotalSeconds) -lt 30)
{
try
{
$ipAddress = Get-CimInstance `
-ClassName MSFT_NetIPAddress `
-Namespace ROOT/StandardCimv2 `
-Filter "((InterfaceAlias = '$Name') AND (AddressFamily = 2))" `
-ErrorAction Stop

if ($ipAddress)
{
$adapterBindingReady = $true
} # if

Write-Verbose -Message ($LocalizedData.WaitingForIPAddressMessage -f $Name)
Start-Sleep -Seconds 1
}
catch
{
Write-Warning -Message ($LocalizedData.GetIPAddressWarning -f $_)
}
} # while

if (-not $ipAddress)
{
throw $LocalizedData.NewNetworkAdapterNotFoundInCIMError
}

# Pull the newly named adapter (to be safe)
$adapter = Get-NetAdapter `
-Name $Name `
-ErrorAction Stop

return $adapter
}
#EndRegion './Public/New-LoopbackAdapter.ps1' 118
#Region './Public/Remove-LoopbackAdapter.ps1' 0
function Remove-LoopbackAdapter
{
[CmdLetBinding()]
param
(
[Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)]
[System.String]
$Name,

[Parameter()]
[switch]
$Force
)

process {
$null = $PSBoundParameters.Remove('Name')

# Check for the existing Loopback Adapter
$adapter = Get-NetAdapter `
-Name $Name `
-ErrorAction SilentlyContinue

# Is the loopback adapter installed?
if (-not $adapter)
{
# Adapter doesn't exist
throw ($LocalizedData.LoopbackAdapterNotFound -f $Name)
}

# Is the adapter Loopback adapter?
if ($adapter.DriverDescription -ne 'Microsoft KM-TEST Loopback Adapter')
{
# Not a loopback adapter - don't uninstall this!
throw ($LocalizedData.NetworkAdapterWrongTypeError -f $Name)
} # if

# Make sure DevCon is installed and return path to executable
$devConExe = (Install-Devcon @PSBoundParameters).FullName

<#
Use Devcon.exe to remove the Microsoft Loopback adapter using the PnPDeviceID.
Requires local Admin privs.
#>
Write-Verbose -Message ($LocalizedData.RemovingLoopbackAdapterMessage -f $Name)
$null = & $devConExe @('remove',"@$($adapter.PnPDeviceID)")
Wait-ForDevconUpdate
}
} # function Remove-LoopbackAdapter
#EndRegion './Public/Remove-LoopbackAdapter.ps1' 49
#Region './suffix.ps1' 0
#EndRegion './suffix.ps1' 1

参考
C:\ProgramData\chocolatey\lib\devcon.portable
C:\ProgramData\chocolatey\bin
C:\Program Files\WindowsPowerShell\Modules\LoopbackAdapter
基于此原理我